package com.xxl.job.admin.controller;

import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.thread.JobRegistryHelper;
import com.xxl.job.admin.dao.IXxlJobGroupDao;
import com.xxl.job.admin.dao.IXxlJobInfoDao;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.registry.RegistHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.bigdata.framework.admin.web.controller.BaseContoroller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * job group controller
 * @author xuxueli 2016-10-02 20:52:56
 */
@Controller
//@RequestMapping("/jobgroup")
public class JobGroupController extends BaseContoroller{

	@Resource
	public IXxlJobInfoDao xxlJobInfoDao;
	@Resource
	public IXxlJobGroupDao xxlJobGroupDao;

	//执行器管理页面
	@RequestMapping("xxl-job-group-list.html")
	public String xxljobgrouplist() {
		return "/modules/xxljob/xxl_job_group_list";
	}
	//执行器管理页面
	@RequestMapping("xxl-job-group-add.html")
	public String xxljobgroupadd() {
		return "/modules/xxljob/xxl_job_group_add";
	}
	//执行器管理——列表
	@RequestMapping("xxljob_group_pageList")
	@ResponseBody
	public void xxljob_group_pageList(HttpServletRequest request,HttpServletResponse response) throws Exception {
		// job admin
		List<String> adminAddressList = JobRegistryHelper.discover(RegistHelper.RegistType.ADMIN.name(), RegistHelper.RegistType.ADMIN.name());
		// job group (executor)
		List<XxlJobGroup> list = xxlJobGroupDao.findAll();
		if (CollectionUtils.isNotEmpty(list)) {
			for (XxlJobGroup group: list) {
				List<String> registryList = null;
				if (group.getAddressType() == 0) {
					registryList = JobRegistryHelper.discover(RegistHelper.RegistType.EXECUTOR.name(), group.getAppName());
				} else {
					if (StringUtils.isNotBlank(group.getAddressList())) {
						registryList = Arrays.asList(group.getAddressList().split(","));
					}
				}
				group.setRegistryList(registryList);
			}
		}
		StringBuffer sb = new StringBuffer();
		
		sb.append("{");
		if(list.size()==0){
			sb.append("\"listsize\":"+0+",");
		}else{
			sb.append("\"listsize\":"+list.size()+",");
		}
		sb.append("\"adminAddressList\":"+formatToJson(adminAddressList)+",");
		sb.append("\"list\":"+formatToJson(list)+"}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	
	//执行器管理——添加保存
	@RequestMapping("xxljob_group_save")
	@ResponseBody
	public void xxljob_group_save(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String result="";
		String id=request.getParameter("id");
		String appName=request.getParameter("appName");
		String title=request.getParameter("title");
		String order=request.getParameter("order");
		String addressType=request.getParameter("addressType");
		String addressList=request.getParameter("addressList");
		// valid
		if (appName==null || StringUtils.isBlank(appName)) {
			result = "{\"result\":\"请输入AppName\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (appName.length()>64) {
			result = "{\"result\":\"AppName长度限制为4~64\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (title==null || StringUtils.isBlank(title)) {
			result = "{\"result\":\"请输入名称\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (order==null || StringUtils.isBlank(order)) {
			result = "{\"result\":\"请输入排序\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (!order.matches("([1-9]+)|([1-9][0-9]+)")) {
			result = "{\"result\":\"请输入整数\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (Integer.parseInt(addressType)!=0) {
			if (StringUtils.isBlank(addressList)) {
				result = "{\"result\":\"手动录入注册方式，机器地址不可为空\"}";
				super.pringWriterToPage(result, "application/json", response);
				return;
			}
			String[] addresss = addressList.split(",");
			for (String item: addresss) {
				if (StringUtils.isBlank(item)) {
					result = "{\"result\":\"机器地址非法\"}";
					super.pringWriterToPage(result, "application/json", response);
					return;
				}
			}
		}
		XxlJobGroup xxlJobGroup = new XxlJobGroup();
		xxlJobGroup.setId(Integer.parseInt(id));
		xxlJobGroup.setAppName(appName);
		xxlJobGroup.setTitle(title);
		xxlJobGroup.setAddressType(Integer.parseInt(addressType));
		xxlJobGroup.setOrder(Integer.parseInt(order));
		xxlJobGroup.setAddressList(addressList);
		int ret = xxlJobGroupDao.save(xxlJobGroup);
		result=ret>0?"{\"result\":\"ok\"}":"{\"result\":\"no\"}";
		super.pringWriterToPage(result, "application/json", response);
	}
	//执行器管理——编辑更新
	@RequestMapping("xxljob_group_update")
	@ResponseBody
	public void xxljob_group_update(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String result="";
		String id=request.getParameter("id");
		String appName=request.getParameter("appName");
		String title=request.getParameter("title");
		String order=request.getParameter("order");
		String addressType=request.getParameter("addressType");
		String addressList=request.getParameter("addressList");
		// valid
		if (appName==null || StringUtils.isBlank(appName)) {
			result = "{\"result\":\"请输入AppName\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (appName.length()>64) {
			result = "{\"result\":\"AppName长度限制为4~64\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (title==null || StringUtils.isBlank(title)) {
			result = "{\"result\":\"请输入名称\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (order==null || StringUtils.isBlank(order)) {
			result = "{\"result\":\"请输入排序\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (!order.matches("([1-9]+)|([1-9][0-9]+)")) {
			result = "{\"result\":\"请输入整数\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (Integer.parseInt(addressType)!=0) {
			if (StringUtils.isBlank(addressList)) {
				result = "{\"result\":\"手动录入注册方式，机器地址不可为空\"}";
				super.pringWriterToPage(result, "application/json", response);
				return;
			}
			String[] addresss = addressList.split(",");
			for (String item: addresss) {
				if (StringUtils.isBlank(item)) {
					result = "{\"result\":\"机器地址非法\"}";
					super.pringWriterToPage(result, "application/json", response);
					return;
				}
			}
		}
		XxlJobGroup xxlJobGroup = new XxlJobGroup();
		xxlJobGroup.setId(Integer.parseInt(id));
		xxlJobGroup.setAppName(appName);
		xxlJobGroup.setTitle(title);
		xxlJobGroup.setAddressType(Integer.parseInt(addressType));
		xxlJobGroup.setOrder(Integer.parseInt(order));
		xxlJobGroup.setAddressList(addressList);
		int ret = xxlJobGroupDao.update(xxlJobGroup);
		result=ret>0?"{\"result\":\"ok\"}":"{\"result\":\"no\"}";
		super.pringWriterToPage(result, "application/json", response);
	}
	//执行器管理——删除
	@RequestMapping("xxljob_group_remove")
	@ResponseBody
	public void xxljob_group_remove(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String result="";
		String id = request.getParameter("id");
		// valid
		int count = xxlJobInfoDao.pageListCount(0, 10, Integer.parseInt(id), null);
		if (count > 0) {
			result = "{\"result\":\"该分组使用中, 不可删除\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}

		List<XxlJobGroup> allList = xxlJobGroupDao.findAll();
		if (allList.size() == 1) {
			result = "{\"result\":\"删除失败, 系统需要至少预留一个默认分组\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}

		int ret = xxlJobGroupDao.remove(Integer.parseInt(id));
		result=ret>0?"{\"result\":\"ok\"}":"{\"result\":\"no\"}";
		super.pringWriterToPage(result, "application/json", response);
	}
	//执行器管理——删除
	@RequestMapping("xxljob_group_get")
	@ResponseBody
	public void xxljob_group_get(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		XxlJobGroup xxlJobGroup = xxlJobGroupDao.load(Integer.parseInt(id));
		String result = formatToJson(xxlJobGroup);
		super.pringWriterToPage(result, "application/json", response);
	}
	/*
	@RequestMapping
	public String index(Model model) {

		// job admin
		List<String> adminAddressList = JobRegistryHelper.discover(RegistHelper.RegistType.ADMIN.name(), RegistHelper.RegistType.ADMIN.name());

		// job group (executor)
		List<XxlJobGroup> list = xxlJobGroupDao.findAll();

		if (CollectionUtils.isNotEmpty(list)) {
			for (XxlJobGroup group: list) {
				List<String> registryList = null;
				if (group.getAddressType() == 0) {
					registryList = JobRegistryHelper.discover(RegistHelper.RegistType.EXECUTOR.name(), group.getAppName());
				} else {
					if (StringUtils.isNotBlank(group.getAddressList())) {
						registryList = Arrays.asList(group.getAddressList().split(","));
					}
				}
				group.setRegistryList(registryList);
			}
		}

		model.addAttribute("adminAddressList", adminAddressList);
		model.addAttribute("list", list);
		return "jobgroup/jobgroup.index";
	}

	@RequestMapping("/save")
	@ResponseBody
	public ReturnT<String> save(XxlJobGroup xxlJobGroup){

		// valid
		if (xxlJobGroup.getAppName()==null || StringUtils.isBlank(xxlJobGroup.getAppName())) {
			return new ReturnT<String>(500, "请输入AppName");
		}
		if (xxlJobGroup.getAppName().length()>64) {
			return new ReturnT<String>(500, "AppName长度限制为4~64");
		}
		if (xxlJobGroup.getTitle()==null || StringUtils.isBlank(xxlJobGroup.getTitle())) {
			return new ReturnT<String>(500, "请输入名称");
		}
		if (xxlJobGroup.getAddressType()!=0) {
			if (StringUtils.isBlank(xxlJobGroup.getAddressList())) {
				return new ReturnT<String>(500, "手动录入注册方式，机器地址不可为空");
			}
			String[] addresss = xxlJobGroup.getAddressList().split(",");
			for (String item: addresss) {
				if (StringUtils.isBlank(item)) {
					return new ReturnT<String>(500, "机器地址非法");
				}
			}
		}

		int ret = xxlJobGroupDao.save(xxlJobGroup);
		return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL;
	}

	@RequestMapping("/update")
	@ResponseBody
	public ReturnT<String> update(XxlJobGroup xxlJobGroup){
		// valid
		if (xxlJobGroup.getAppName()==null || StringUtils.isBlank(xxlJobGroup.getAppName())) {
			return new ReturnT<String>(500, "请输入AppName");
		}
		if (xxlJobGroup.getAppName().length()>64) {
			return new ReturnT<String>(500, "AppName长度限制为4~64");
		}
		if (xxlJobGroup.getTitle()==null || StringUtils.isBlank(xxlJobGroup.getTitle())) {
			return new ReturnT<String>(500, "请输入名称");
		}
		if (xxlJobGroup.getAddressType()!=0) {
			if (StringUtils.isBlank(xxlJobGroup.getAddressList())) {
				return new ReturnT<String>(500, "手动录入注册方式，机器地址不可为空");
			}
			String[] addresss = xxlJobGroup.getAddressList().split(",");
			for (String item: addresss) {
				if (StringUtils.isBlank(item)) {
					return new ReturnT<String>(500, "机器地址非法");
				}
			}
		}

		int ret = xxlJobGroupDao.update(xxlJobGroup);
		return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL;
	}

	@RequestMapping("/remove")
	@ResponseBody
	public ReturnT<String> remove(int id){

		// valid
		int count = xxlJobInfoDao.pageListCount(0, 10, id, null);
		if (count > 0) {
			return new ReturnT<String>(500, "该分组使用中, 不可删除");
		}

		List<XxlJobGroup> allList = xxlJobGroupDao.findAll();
		if (allList.size() == 1) {
			return new ReturnT<String>(500, "删除失败, 系统需要至少预留一个默认分组");
		}

		int ret = xxlJobGroupDao.remove(id);
		return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL;
	}
*/
}
